<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            label-width="130px"
            label-position="right"
            @search="search"
            @reset="reset('queryForm')"
        >
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item :label="$t('abnormal.abnormalCategory')">
                        <DictSelect
                            v-model="queryForm.classCode"
                            :data="options.classCodes"
                            :clearable="false"
                            @change="handlerClassCodeChange"
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('abnormal.abnormalType')">
                        <el-select
                            v-model="queryForm.id"
                            filterable
                            style="width: 100%"
                        >
                            <el-option
                                v-for="item in options.typeCodes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('abnormal.allowStudentApply')">
                        <DictSelect
                            v-model="queryForm.studentApply"
                            :data="options.studentApply"
                            :clearable="false"
                        ></DictSelect>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('label.trainingLevel')">
                        <DictSelect
                            :multiple="true"
                            v-model="queryForm.trainingLevel"
                            :data="options.trainingLevel"
                            :clearable="false"
                        ></DictSelect>
                    </el-form-item>
                </el-col>
            </el-row>
        </ConditionCard>
        <el-card shadow="never">
            <el-row type="flex" align="middle">
                <el-col class="edu-page-title">{{
                    $t("abnormal.abnormalTypeList")
                }}</el-col>
                <el-col class="text-right">
                    <el-button
                        style="margin-bottom:16px"
                        type="primary"
                        @click="showAddAbnormalTypeModal"
                        >{{ $t("message.add") }}</el-button
                    >
                </el-col>
            </el-row>
            <edu-table
                stripe
                style="width: 100%"
                :data="tableData.list"
                :total="tableData.total_"
                :pageNum="queryForm.pageNum_"
                :selection="false"
                :order="false"
                @page-change="handleCurrentChange"
            >
                <el-table-column
                    :label="$t('abnormal.abnormalCategoryCode')"
                    prop="classCode"
                    :show-overflow-tooltip="true"
                    width="120"
                ></el-table-column>
                <el-table-column
                    :label="$t('abnormal.abnormalCategory')"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="props">{{
                        props.row.classCodeI18n
                    }}</template>
                </el-table-column>
                <el-table-column
                    :label="$t('abnormal.abnormalTypeCode')"
                    prop="code"
                    :show-overflow-tooltip="true"
                    width="120"
                ></el-table-column>
                <el-table-column
                    :label="$t('abnormal.abnormalType')"
                    prop="name"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    :label="$t('abnormal.allowStudentApply')"
                    prop="studentApply"
                    :show-overflow-tooltip="true"
                    width="120"
                >
                    <template slot-scope="props">{{
                        props.row.studentApply | yesOrNo
                    }}</template>
                </el-table-column>
                <el-table-column
                    :label="$t('label.trainingLevel')"
                    prop="trainingLevel"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="props">{{
                        props.row.trainingLevelName
                    }}</template>
                </el-table-column>
                <el-table-column
                    :label="$t('abnormal.changeType')"
                    prop="changeType"
                    :show-overflow-tooltip="true"
                    width="120"
                >
                    <template slot-scope="props">
                        {{
                            props.row.changeType
                                | getCodeByName(options.changeType)
                        }}
                    </template>
                </el-table-column>
                <el-table-column
                    :label="$t('abnormal.inUse')"
                    prop="inUse"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="props">
                        <el-tag
                            :type="props.row.inUse ? 'success' : 'danger'"
                            >{{
                                props.row.inUse | getCodeByName(options.inUse)
                            }}</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    :label="$t('abnormal.abnormalReason')"
                    prop="grade"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="props">
                        <el-tag
                            :type="
                                props.row.customizeReason == 1
                                    ? 'success'
                                    : 'danger'
                            "
                        >
                            {{
                                props.row.customizeReason == 1
                                    ? $t("abnormal.configed")
                                    : $t("abnormal.unConfiged")
                            }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    :label="$t('abnormal.abnormalFieldAuth')"
                    prop="grade"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="props">
                        <el-tag
                            :type="
                                props.row.customizeFieldAuth == 1
                                    ? 'success'
                                    : 'danger'
                            "
                        >
                            {{
                                props.row.customizeFieldAuth == 1
                                    ? $t("abnormal.configed")
                                    : $t("abnormal.unConfiged")
                            }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    :label="$t('abnormal.abnormalField')"
                    prop="grade"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="props">
                        <el-tag
                            :type="
                                props.row.customizeField == 1
                                    ? 'success'
                                    : 'danger'
                            "
                        >
                            {{
                                props.row.customizeField == 1
                                    ? $t("abnormal.configed")
                                    : $t("abnormal.unConfiged")
                            }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('message.operating')" width="200" fixed="right">
                    <template slot-scope="props">
                        <el-button
                            type="text"
                            size="mini"
                            @click="setAbnormalType(props.row.id)"
                            >{{
                                $t("abnormal.abnormalDetailSetting")
                            }}</el-button
                        >
                        <el-button
                            type="text"
                            size="mini"
                            @click="editItem(props.row)"
                            >{{ $t("message.edit") }}</el-button
                        >
                        <el-button
                        type="text"
                        size="mini"
                        @click="deleteItem(props.row)"
                        >{{ $t("abnormal.delete") }}</el-button
                        >
                    </template>
                </el-table-column>
            </edu-table>
        </el-card>
        <!--添加/修改异动类型弹窗-->
        <edu-dialog
            ref="abnormalTypeDialog"
            size="medium"
            @close="closeDialog"
            :title="
                flagEdit
                    ? $t('abnormal.editAbnormalType')
                    : $t('abnormal.addAbnormalType')
            "
        >
            <edu-dialog
                title="提示"
                ref="innerDialog"
                class="tip-item"
                append-to-body
            >
                返回将不会保存当前设置，是否确定？
                <span slot="buttons">
                    <el-button @click="cancleInner">取消</el-button>
                    <el-button type="primary" @click="confirmInner"
                        >确定</el-button
                    >
                    <el-button type="primary" @click="saveAndCloseInner"
                        >保存并关闭</el-button
                    >
                </span>
            </edu-dialog>
            <el-form
                ref="operateForm"
                :model="operateForm"
                :rules="abnormalFormRules"
                label-width="110px"
                label-position="right"
                size="mini"
                class="bg-white"
            >
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('abnormal.abnormalCategory')"
                            prop="classCode"
                        >
                            <DictSelect
                                v-model="operateForm.classCode"
                                :data="options.classCodes"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="operateForm.code">
                        <el-form-item
                            :label="$t('abnormal.abnormalTypeCode')"
                            prop="code"
                        >
                            <el-input
                                :disabled="true"
                                v-model="operateForm.code"
                                type="text"
                                style="width:100%"
                                maxlength="6"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('abnormal.abnormalType')"
                            prop="name"
                        >
                            <el-input
                                v-model="operateForm.name"
                                type="text"
                                style="width:100%"
                                maxlength="8"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('label.trainingLevel')"
                            prop="trainingLevel"
                        >
                            <DictSelect
                                :multiple="true"
                                v-model="operateForm.trainingLevel"
                                :data="options.trainingLevel"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('abnormal.allowStudentApply')"
                            prop="studentApply"
                        >
                            <DictSelect
                                v-model="operateForm.studentApply"
                                :data="options.studentApply"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('abnormal.changeType')"
                            prop="changeType"
                        >
                            <DictSelect
                                v-model="operateForm.changeType"
                                :data="options.changeType"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('abnormal.inUse')"
                            prop="inUse"
                        >
                            <DictSelect
                                v-model="operateForm.inUse"
                                :data="options.inUse"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('abnormal.isShowChangeEndTime')"
                            prop="isShowChangeEndTime"
                        >
                            <DictSelect
                                v-model="operateForm.isShowChangeEndTime"
                                :data="options.isShowChangeEndTime"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="OA文号" prop="oaNumb">
                            <DictSelect
                                v-model="operateForm.oaNumb"
                                :data="options.oaList"
                                :clearable="false"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="撤销时限">
                            <el-select
                                v-model="operateForm.revocationTimeLimit"
                                placeholder="全部"
                                clearable
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.revocationTimeList"
                                    :key="item.key"
                                    :label="item.label"
                                    :value="item.key"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item :label="$t('message.remark')">
                            <el-input
                                v-model="operateForm.remark"
                                :rows="4"
                                type="textarea"
                                style="width:100%"
                                maxlength="255"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="buttons">
                <el-button @click="cancelDialog">{{
                    $t("label.back")
                }}</el-button>
                <el-button type="primary" @click="saveAndSetAbnormalType">{{
                    $t("abnormal.abnormalSet")
                }}</el-button>
                <el-button
                    type="primary"
                    @click="saveAbnormal('operateForm')"
                    >{{ $t("message.save") }}</el-button
                >
            </span>
        </edu-dialog>
    </div>
</template>

<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import * as API from "common/src/api/abnormalType/abnormal";
import { yesOrNo } from "common/src/filters/commonFilter";
//getAbnormalTypeByClassCode
export default {
    name: "adnormalTypeList",
    data() {
        // 验证异动类型代码，包括格式验证和校验是否存在同名
        // let validateAbnormalCode = (rule, value, callback) => {
        //     if (!/^\d{6}$/.test(value)) {
        //         return callback(new Error("异动类型代码必须为六位数字"));
        //     }
        //     let param = {
        //         code: value
        //     };
        //     if (!this.flagEdit) {
        //         param.id = this.operateForm.id;
        //     }
        //     API.checkIsExistCode(param).then(res => {
        //         let { code, data } = res;
        //         if (code === 200 && data === "failed")
        //             callback(new Error(this.$t("abnormal.existAbnormalCode")));
        //         else callback();
        //     });
        // };
        // 验证异动大类下面异动类型名称都不能重复
        let validateAbnormalName = (rule, value, callback) => {
            let param = {
                classCode: this.operateForm.classCode,
                name: value
            };
            param.id = this.operateForm.id;
            API.checkIsExistName(param).then(res => {
                let { code, data } = res;
                if (code === 200 && data === "failed")
                    callback(new Error(this.$t("abnormal.existAbnormal")));
                else callback();
            });
        };
        return {
            queryForm: {
                classCode: "",
                id: "",
                studentApply: "",
                trainingLevel: [],
                pageSize_: 20,
                pageNum_: 1,
                total_: 0
            },
            operateForm: {
                classCode: "",
                code: "",
                name: "",
                trainingLevel: [],
                studentApply: "",
                changeType: "",
                inUse: 1,
                isShowChangeEndTime: 1,
                remark: "",
                oaNumb: "",
                revocationTimeLimit: ""
            },
            abnormalFormRules: {
                classCode: [
                    {
                        required: true,
                        trigger: "change",
                        message: this.$t('abnormal.invalidAbnormalCategory')
                    }
                ],
                // code: [
                //     {
                //         required: true,
                //         message: this.$t("abnormal.invalidAbnormalTypeCode")
                //     },
                //     {
                //         validator: validateAbnormalCode,
                //         trigger: "blur"
                //     }
                // ],
                name: [
                    {
                        required: true,
                        message: this.$t("abnormal.invalidAbnormalType")
                    },
                    {
                        validator: validateAbnormalName,
                        trigger: "blur"
                    }
                ],
                trainingLevel: [
                    {
                        required: true,
                        trigger: "change",
                        message: this.$t("abnormal.invalidTrainingLevel")
                    }
                ],
                studentApply: [
                    {
                        required: true,
                        trigger: "change",
                        message: this.$t("abnormal.invalidStudentApply")
                    }
                ],
                changeType: [
                    {
                        required: true,
                        trigger: "change",
                        message: this.$t("abnormal.invalidChangeType")
                    }
                ],
                inUse: [
                    {
                        required: true,
                        trigger: "change",
                        message: this.$t("abnormal.invalidInUse")
                    }
                ],
                isShowChangeEndTime: [
                    {
                        required: true,
                        trigger: "change",
                        message: this.$t("abnormal.isShowSwitch")
                    }
                ],
                oaNumb: [
                    {
                        required: true,
                        trigger: "change",
                        message: "OA文号不能为空。"
                    }
                ]
            },
            options: {
                revocationTimeList: [
                    {
                        label: "一周",
                        key: "week"
                    },
                    {
                        label: "一月",
                        key: "month"
                    },
                    {
                        label: "本学期",
                        key: "term"
                    },
                    {
                        label: "本学年",
                        key: "year"
                    }
                ],
                //  异动大类列表
                classCodes: [],
                // 异动类型列表
                typeCodes: [],
                // 是否学生申请
                studentApply: [
                    {
                        value: 1,
                        label: this.$t("message.yes")
                    },
                    {
                        value: 0,
                        label: this.$t("message.no")
                    }
                ],
                isShowChangeEndTime: [
                    {
                        value: 1,
                        label: this.$t("message.yes")
                    },
                    {
                        value: 0,
                        label: this.$t("message.no")
                    }
                ],
                // 更新类型
                changeType: [
                    {
                        value: 0,
                        label: "根据异动时间生效"
                    },
                    {
                        value: 1,
                        label: "立即生效"
                    }
                ],
                // 是否使用中
                inUse: [
                    {
                        value: 0,
                        label: this.$t("abnormal.notUsing")
                    },
                    {
                        value: 1,
                        label: this.$t("abnormal.using")
                    }
                ],
                oaList: [
                    {
                        value: 0,
                        label: "否"
                    },
                    {
                        value: 1,
                        label: "是"
                    }
                ],
                trainingLevel: []
            },
            // 列表数据
            tableData: {
                list: []
            },

            // 弹窗标题，根据不同的操作显示新增和修改异动类型
            dialogTitle: "",
            // 标识弹窗是否是编辑状态
            flagEdit: false
        };
    },
    filters: {
        yesOrNo,
        // 过滤器，根据code找name，列表数据id转文字时用
        getCodeByName(val, arr) {
            let item = arr.find(i => i.value === val);
            if (item) {
                return item.label;
            }
            return "";
        }
    },
    created() {
        this.init();
    },
    methods: {
        init() {
            // 获取数据字典数据
            this.initOptions();
            // 获取异动类型列表
            this.getAbnormalList();
        },
        initOptions() {
            let _this = this;
            let data = {
                lang: _this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["G_XJDL", "X_PYCC"]
            };
            queryDic(data)
                .then(res => {
                    if (res.code === 200) {
                        let dataCopy = {
                            classCodes: [],
                            trainingLevel: []
                        };
                        UTILS.fillSelect(
                            {
                                classCodes: "G_XJDL",
                                trainingLevel: "X_PYCC"
                            },
                            res.data,
                            dataCopy
                        );
                        let arrayFore = dataCopy.classCodes.filter(
                            e => e.label !== "其他"
                        );
                        let arrayBehind = dataCopy.classCodes.filter(
                            e => e.label == "其他"
                        );
                        _this.options.classCodes = [
                            ...arrayFore,
                            ...arrayBehind
                        ];
                        _this.options.trainingLevel = dataCopy.trainingLevel;
                    }
                })
                .catch(error => {
                    throw error;
                });
        },
        // 分页页数变化时回调
        handleCurrentChange(val) {
            this.queryForm.pageSize_ = val.pageSize;
            this.queryForm.pageNum_ = val.pageNum;
            this.getAbnormalList();
        },
        // 异动大类变化时的回调，用于根据大类id查询该大类下面所有异动类型
        handlerClassCodeChange(val) {
            this.queryForm.id = ""
            API.getAbnormalTypeByClassCode(val).then(res => {
                let { code, data } = res;
                if (code === 200) {
                    this.options.typeCodes = data;
                }
            });
        },
        // 获取异动类型列表
        getAbnormalList() {
            let params = _.cloneDeep(this.queryForm);
            API.getAbnormalTypeList(
                Object.assign(params, {
                    trainingLevel: params.trainingLevel + ""
                })
            ).then(res => {
                let {
                    code,
                    data: { list, total_ }
                } = res;
                if (code === 200) {
                    this.tableData.list = list;
                    this.tableData.total_ = total_;
                }
            });
        },
        // 点击筛选时的回调
        search() {
            this.getAbnormalList();
        },
        // 点击重置按钮时的回调
        reset() {
            this.queryForm.classCode = '';
            this.queryForm.code = '';
            this.queryForm.studentApply = '';
            this.queryForm.id = '';
            this.queryForm.trainingLevel = [];
            this.options.typeCodes = [];
            this.getAbnormalList();
        },
        // 点击列表中的设置异动类型回调
        setAbnormalType(id) {
            this.$router.push({
                name: "abnormalTypeSetting",
                params: {
                    id
                }
            });
        },
        // 弹框内点击设置异动类型按钮，先保存再跳到设置页面
        saveAndSetAbnormalType() {
            this.$refs["operateForm"].validate(valid => {
                if (valid) {
                    if (!this.flagEdit)
                        this.$eduConfirm("是否确定保存当前设置？", "提示", {
                            confirmButtonText: "是",
                            cancelButtonText: "否"
                        }).then(() => {
                            let promise = this.saveOrUpdateAbnormal();
                            promise.then(res => {
                                let { code, data } = res;
                                if (code === 200 && data) {
                                    this.setAbnormalType(data.id);
                                }
                            });
                        });
                    else {
                        let promise = this.saveOrUpdateAbnormal();
                        promise.then(res => {
                            let { code, data } = res;
                            if (code === 200 && data) {
                                this.setAbnormalType(data.id);
                            }
                        });
                    }
                }
            });
        },
        // 控制添加/修改弹窗的显示隐藏
        showAddAbnormalTypeModal() {
            this.flagEdit = false;
            // this.showDialog = true;
            this.$refs.abnormalTypeDialog.open();
        },
        editItem(item) {
            let operateForm = this.operateForm;
            for (var key in operateForm) {
                if (key == "trainingLevel") {
                    operateForm[key] = item[key].split(",");
                } else if (key == "oaNumb") {
                    operateForm[key] = +item[key];
                } else {
                    operateForm[key] = item[key];
                }
            }
            this.flagEdit = true;
            // 编辑时修改异动类型校验（只有非空校验）
            if (this.flagEdit) {
                this.abnormalFormRules.name[0] = {
                    required: true,
                    message: this.$t("abnormal.invalidAbnormalType")
                };
                // this.abnormalFormRules.code = [
                //     {
                //         required: true,
                //         message: this.$t("abnormal.invalidAbnormalTypeCode")
                //     }
                // ];
                operateForm.id = item.id;
            }
            // this.showDialog = true;
            this.$refs.abnormalTypeDialog.open();
        },
        deleteItem(item) {
            let parm = [
                {
                    id:item.id,
                    code: item.code
                }
            ]
                this.$eduConfirm("确认删除？", "提示", {
                        confirmButtonText: "是",
                        cancelButtonText: "否"
                    }).then(() => {
                    API.deleteAbnormalType(parm).then(res=> {
                    if(res.code === 200) {
                        this.$message({
                            type: "success",
                            message:'删除成功'
                        });
                        this.getAbnormalList();
                    }
                })
            });
        },
        // 关闭弹窗重置 operateForm
        closeDialog() {
            // 重置字段
            this.$refs.operateForm.resetFields();
            let operateForm = this.operateForm;
            for (var key in operateForm) {
                if (key == "trainingLevel") {
                    operateForm[key] = [];
                } else if (key == "inUse") {
                    operateForm[key] = 1;
                } else {
                    operateForm[key] = "";
                }
            }
        },
        cancelDialog() {
            // this.showDialog = false;
            let operateForm = this.operateForm;
            let values = Object.values(operateForm).filter(item => {
                return item;
            });
            if (values.length) {
                this.$refs.innerDialog.open();
            } else {
                this.$refs.abnormalTypeDialog.close();
            }
        },
        async saveOrUpdateAbnormal() {
            let params = _.cloneDeep(this.operateForm);
            params = Object.assign(params, {
                trainingLevel: params.trainingLevel + ""
            });
            return this.flagEdit
                ? await API.updateAbnormalType(params)
                : await API.addAbnormalType(params);
        },
        // 保存异动类型
        saveAbnormal(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let promise = this.saveOrUpdateAbnormal();
                    promise.then(res => {
                        let { code } = res;
                        if (code === 200) {
                            let message = this.flagEdit
                                ? this.$t("message.editSuccess")
                                : this.$t("message.saveSuccess");
                            this.$message({
                                type: "success",
                                message
                            });
                            this.$refs.abnormalTypeDialog.close();
                            this.cancleInner();
                            if (this.queryForm.classCode) {
                                this.handlerClassCodeChange(
                                    this.queryForm.classCode
                                );
                            }
                            this.search();
                        }
                    });
                } else {
                    this.cancleInner();
                }
            });
        },
        // innerDialog 相关方法
        cancleInner() {
            this.$refs.innerDialog.close();
        },
        confirmInner() {
            this.$refs.abnormalTypeDialog.close();
            this.cancleInner();
        },
        saveAndCloseInner() {
            this.saveAbnormal("operateForm");
        }
    }
};
</script>
<style lang="scss" scoped>
</style>
